import api from '../../../api/index';
import common from '../../../common/index';
import { DetailDataType } from '../../../types';

const app = getApp();

Page({
  data: {
    uid: '',
    id: '',
    author_id: 'aispire',
    detailData: null as DetailDataType | null,
    loading: true,
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    pcenterPageShow: false,
    commentText: '', // 评论输入框文本
    // 当前用户已关注的用户 uid 列表
    followUidList: [] as string[],
    // 保存到智库相关
    selectDirShow: false,
    dirList: [] as any[],
    fieldNames: { text: 'dir_name', value: 'dir_id', children: 'children' } as any,
    cacheCurrentDirItem: { dir_id: '', dir_name: '' } as any,
    // 标签相关
    contentTags: [] as string[], // 当前内容所属标签
    availableTags: [] as string[], // 用户所有标签
    showTagSelector: false, // 标签选择弹窗
    selectedTag: '', // 选中的标签
    // 猜你喜欢相关
    similarLoading: false,
    similarError: '',
    similarList: [] as any[],
    similarLeftColumn: [] as any[],
    similarRightColumn: [] as any[],
  },

  onLoad(options: any) {
    console.log('=== 详情页面加载 ===');
    console.log('页面参数options:', options);
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    // 获取用户信息中的uid，尝试多种方式
    const userInfo = common.getAppUserInfo();
    let uid = userInfo?.uid || userInfo?.userId;
    
    // 如果从app.globalData获取失败，尝试从本地存储获取
    if (!uid) {
      const localUid = common.getLocalUid();
      uid = localUid;
      console.log('从本地存储获取uid:', localUid);
    }
    
    // 如果仍然没有uid，尝试从app.globalData重新获取
    if (!uid) {
      const app = getApp();
      uid = app.globalData?.user?.uid;
      console.log('从app.globalData重新获取uid:', uid);
    }
    
    console.log('最终使用的uid:', uid);
    console.log('用户信息:', userInfo);
    
    const id = options.id || "bcb6cea457844ff3312879555db76d0e";
    const author_id = options.author_id || "aispire";
    
    console.log('使用的参数:', { uid, id, author_id });
    
    this.setData({ uid, id, author_id });
    
    // 如果有uid，获取关注列表和详情数据
    if (uid) {
      // 刚进入页面即获取关注列表
      this.fetchFollowList();
      // 直接获取详情数据，不需要验证id
      this.fetchDetailData();
    } else {
      console.warn('未获取到用户uid，部分功能可能受限');
      // 仍然获取详情数据，但某些功能可能受限
      this.fetchDetailData();
    }
  },

  onShow() {
    // 页面显示时尝试更新用户uid
    this.updateUserUid();
  },

  async fetchDetailData() {
    try {
      this.setData({ loading: true });
      
      console.log('=== 调用详情接口 ===');
      console.log('请求参数:', { uid: this.data.uid, id: this.data.id, author_id: this.data.author_id });
      
      const res = await api.getInspirationDetail({
        uid: this.data.uid,
        id: this.data.id
      });
      
      console.log('接口返回数据:', res);
      
      if (res.data) {
        console.log('设置详情数据:', res.data);
        console.log('AI标题:', res.data.ai_title);
        console.log('接口返回的标签数据:', res.data.tag);
        
        // 设置详情数据
        this.setData({ detailData: res.data, loading: false });
        
        // 设置内容标签 - 从接口返回的数据中获取
        if (res.data.tag && Array.isArray(res.data.tag)) {
          this.setData({ contentTags: res.data.tag });
          console.log('设置内容标签:', res.data.tag);
        } else {
          console.log('接口未返回标签数据或格式不正确，tag字段:', res.data.tag);
        }
        
        // 基于已加载的关注列表设置关注状态
        if (Array.isArray(this.data.followUidList) && res.data.uid) {
          const followed = this.data.followUidList.includes(res.data.uid);
          this.setData({ 'detailData.is_followed': followed });
          console.log('根据关注列表设置作者关注状态:', followed);
        }
        
        // 获取用户的点赞、收藏和关注状态
        this.fetchUserStatus();
        // 获取猜你喜欢
        this.fetchSimilarRecommendations();
      } else {
        wx.showToast({ title: '获取详情失败', icon: 'error' });
        setTimeout(() => wx.navigateBack(), 1500);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
      wx.showToast({ title: '网络错误', icon: 'error' });
      setTimeout(() => wx.navigateBack(), 1500);
    } finally {
      this.setData({ loading: false });
    }
  },

  async fetchSimilarRecommendations() {
    if (!this.data.id) return;
    try {
      this.setData({ similarLoading: true, similarError: '' });
      const requestUid = Number(this.data.uid) || 430;
      const res: any = await api.getSimilarInspiration({
        uid: requestUid,
        id: this.data.id,
        similar_num: 6
      });
      const rawList: any[] = Array.isArray(res?.data) ? res.data : [];
      const transformed = this.transformSimilarData(rawList);
      this.setData({
        similarList: transformed
      });
      this.distributeSimilarData(transformed);
    } catch (error) {
      console.error('获取猜你喜欢失败:', error);
      this.setData({
        similarError: '猜你喜欢加载失败，请稍后重试',
        similarList: [],
        similarLeftColumn: [],
        similarRightColumn: []
      });
    } finally {
      this.setData({ similarLoading: false });
    }
  },

  transformSimilarData(list: any[]) {
    return list
      .filter((item: any) => item && (item.id || item.content_id))
      .map((item: any) => {
        const inspirationId = item.id || item.content_id;
        return {
          id: inspirationId,
          uid: item.uid || '',
          ai_title: item.ai_title || item.title || '',
          image: item.image_url || item.image || '',
          avatar: item.icon || item.avatar || '',
          username: item.nickname || item.uid || '',
          collection: Number(item.collection ?? item.collect_count ?? 0),
          is_collected: !!item.is_collected,
          height: item.height || 278,
          link: item.link || ''
        };
      });
  },

  distributeSimilarData(list: any[]) {
    const left: any[] = [];
    const right: any[] = [];
    let leftHeight = 0;
    let rightHeight = 0;

    list.forEach((item: any) => {
      const itemHeight = item.height || 278;
      if (leftHeight <= rightHeight) {
        left.push(item);
        leftHeight += itemHeight;
      } else {
        right.push(item);
        rightHeight += itemHeight;
      }
    });

    this.setData({
      similarLeftColumn: left,
      similarRightColumn: right
    });
  },

  // 动态更新用户uid
  updateUserUid(): void {
    const userInfo = common.getAppUserInfo();
    let uid = userInfo?.uid || userInfo?.userId;
    
    if (!uid) {
      const localUid = common.getLocalUid();
      uid = localUid;
    }
    
    if (!uid) {
      const app = getApp();
      uid = app.globalData?.user?.uid;
    }
    
    if (uid && uid !== this.data.uid) {
      console.log('更新用户uid:', { 旧uid: this.data.uid, 新uid: uid });
      this.setData({ uid });
      
      // 重新获取用户相关数据
      this.fetchFollowList();
      this.fetchUserStatus();
    }
  },

  // 获取目录（弹窗使用）
  async fetchDirList() {
    try {
      const res: any = await api.getDirFileList({ uid: this.data.uid, dir_id: '' });
      const list: any[] = (res && Array.isArray(res.directories)) ? res.directories : [];
      const dirList = [{ dir_id: '', dir_name: '所有文件夹' }].concat(list);
      // 清理 children 空数组以适配级联组件
      const reset = (dir: any) => {
        if (dir.children && dir.children.length) {
          dir.children.forEach((cd: any) => reset(cd));
        } else {
          delete dir.children;
        }
      };
      dirList.forEach(reset);
      this.setData({ dirList });
    } catch (e) {
      this.setData({ dirList: [] });
    }
  },

  // 打开"保存到智库"文件夹选择弹窗
  async onSaveToKnowledge() {
    // 动态更新用户uid
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        })
      }, 3000)
      return
    }
    if (!this.data.uid || !this.data.detailData) return;
    await this.fetchDirList();
    this.setData({ selectDirShow: true });
  },

  // 选择目录变更
  handleSelectDirChange(e: any) {
    const selectedOptions = e.detail.selectedOptions || [];
    const selectItem = selectedOptions[selectedOptions.length - 1] || { dir_id: '', dir_name: '' };
    this.setData({ cacheCurrentDirItem: selectItem });
  },

  // 关闭目录弹窗
  handleSelectDirClose() {
    this.setData({ selectDirShow: false });
  },

  // 确认选择目录，执行保存逻辑（与移动文件后续一致：这里调用同步到知识库接口）
  async handleSelectDirConfirm() {
    if (!this.data.detailData) return;
    const dir = this.data.cacheCurrentDirItem || { dir_id: '', dir_name: '' };
    // 同步文档到知识库（沿用 inspection 页的接口）
    try {
      wx.showLoading({ title: '保存中' });
      const item: any = this.data.detailData;
      const user = common.getAppUserInfo();
      const currentUid = (user && user.uid) ? user.uid : this.data.uid;
      const syncParams = {
        ...item,
        uid: currentUid,
        parent_dir_id: dir.dir_id,
        dir_name: dir.dir_name,
        content_id: item.id,
        title: item.title,
        ai_title: item.ai_title,
        content: item.content || '',
        author: item.uid,
        publish_time: item.publish_time || new Date().toISOString()
      };
      const res: any = await api.synchronizeDocToKnowledge(syncParams);
      if (res && res.status === 'success') {
        // 同步成功后，调用保存接口标记
        const saveRes: any = await api.saveInspiration({ uid: currentUid, id: item.id });
        wx.hideLoading();
        if (saveRes && saveRes.status === 'success') {
          this.setData({ selectDirShow: false, 'detailData.is_save': true });
          wx.showToast({ title: '已保存到智库', icon: 'success' });
        } else {
          wx.showToast({ title: saveRes?.message || '保存失败', icon: 'error' });
        }
      } else {
        wx.hideLoading();
        wx.showToast({ title: res?.message || '保存失败', icon: 'error' });
      }
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误，请重试', icon: 'error' });
    }
  },

  // 获取当前用户的关注列表
  async fetchFollowList() {
    try {
      console.log('=== 获取关注列表 ===');
      const res: any = await api.getInspirationFollowUserList({ uid: this.data.uid });
      console.log('关注列表接口返回:', res);
      // 兼容多种返回结构
      const list: any[] = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : []);
      const followUids = list
        .map((item: any) => item?.uid || item?.follow_uid)
        .filter((x: any) => typeof x === 'string' && x);
      console.log('解析后的关注 uid 列表:', followUids);
      this.setData({ followUidList: followUids });
      // 如果详情已加载，立即基于关注列表刷新作者关注状态
      if (this.data.detailData?.uid) {
        const followed = followUids.includes(this.data.detailData.uid);
        this.setData({ 'detailData.is_followed': followed });
        console.log('刷新作者关注状态(基于关注列表):', followed);
      }
    } catch (error) {
      console.error('获取关注列表失败:', error);
      this.setData({ followUidList: [] });
    }
  },

  onBackClick() {
    console.log('=== 返回按钮点击 ===');
    
    // 检查是否有上一页
    const pages = getCurrentPages();
    console.log('当前页面栈:', pages.length);
    
    if (pages.length > 1) {
      console.log('有上一页，执行返回');
      wx.navigateBack({
        delta: 1,
        fail: (err) => {
          console.error('返回失败:', err);
          // 如果返回失败，跳转到首页
          wx.switchTab({
            url: '/pages/inspection/inspection'
          });
        }
      });
    } else {
      console.log('没有上一页，跳转到灵感广场');
      // 如果没有上一页，跳转到灵感广场
      wx.switchTab({
        url: '/pages/inspection/inspection'
      });
    }
  },

  // 显示个人中心页面
  showPcenterPage() {
    this.setData({
      pcenterPageShow: true
    });
  },

  // 关闭个人中心页面
  closePcenterPage() {
    this.setData({
      pcenterPageShow: false
    });
  },

  async onCollectClick() {
    // 动态更新用户uid
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        })
      }, 3000)
      return
    }
    
    if (!this.data.detailData) return;
    
    try {
      console.log('=== 收藏操作开始 ===');
      console.log('当前detailData:', this.data.detailData);
      console.log('当前is_collected:', this.data.detailData.is_collected);
      console.log('当前collection数量:', this.data.detailData.collection);
      
      // 检查是否有专门的收藏状态字段，如果没有则使用数量判断
      const isCollected = this.data.detailData.is_collected !== undefined 
        ? this.data.detailData.is_collected 
        : (this.data.detailData.collection > 0);
      
      const action = isCollected ? 'cancel' : 'collect';
      
      console.log('=== 调用收藏接口 ===');
      console.log('计算出的收藏状态:', isCollected);
      console.log('请求参数:', { 
        uid: this.data.uid, 
        id: this.data.id, 
        action 
      });
      
      const res = await api.toggleCollection({
        uid: this.data.uid,
        id: this.data.id,
        action
      });
      
      console.log('收藏接口返回:', res);
      
      // 使用类型断言处理接口返回数据
      const resData = res as any;
      
      if (resData.status === 'success') {
        // 更新本地状态
        const detailData = { ...this.data.detailData! };
        
        if (isCollected) {
          // 取消收藏
          detailData.is_collected = false;
          detailData.collection = Math.max(0, (detailData.collection || 0) - 1);
          console.log('取消收藏后状态:', { is_collected: detailData.is_collected, collection: detailData.collection });
        } else {
          // 添加收藏
          detailData.is_collected = true;
          detailData.collection = (detailData.collection || 0) + 1;
          console.log('添加收藏后状态:', { is_collected: detailData.is_collected, collection: detailData.collection });
        }
        
        this.setData({ detailData });
        console.log('状态更新完成，新的detailData:', detailData);
        
        wx.showToast({
          title: isCollected ? '已取消收藏' : '已收藏',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: resData.message || '操作失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'error'
      });
    }
  },

  onCommentInput(e: any) {
    this.setData({
      commentText: e.detail.value
    });
  },

  async onCommentSubmit() {
    // 动态更新用户uid
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        })
      }, 3000)
      return
    }
    
    const { commentText, uid, id } = this.data;
    
    if (!commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    try {
      console.log('=== 发表评论开始 ===');
      console.log('评论内容:', commentText.trim());
      console.log('请求参数:', {
        uid,
        id,
        action: 'add',
        comment: commentText.trim()
      });

      const res = await api.commentAction({
        uid,
        id,
        action: 'add',
        comment: commentText.trim()
      });

      console.log('评论接口返回:', res);

      // 使用类型断言处理接口返回数据
      const resData = res as any;

      if (resData.status === 'success') {
        // 评论成功后，重新获取详情数据以更新评论列表
        await this.fetchDetailData();
        
        // 清空输入框
        this.setData({ commentText: '' });

        wx.showToast({
          title: '评论发表成功',
          icon: 'success',
          duration: 1500
        });
      } else {
        wx.showToast({
          title: resData.message || '评论发表失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('评论发表失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'error'
      });
    }
  },

  // 删除评论
  async onDeleteComment(e: any) {
    const { commentId } = e.currentTarget.dataset;
    const { uid, id } = this.data;
    
    if (!commentId) {
      console.error('评论ID为空');
      wx.showToast({
        title: '评论ID为空',
        icon: 'error'
      });
      return;
    }

    // 二次确认对话框
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      confirmText: '删除',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          try {
            console.log('=== 删除评论开始 ===');
            console.log('评论ID:', commentId);
            console.log('请求参数:', { uid, id, action: 'delete', comment_id: commentId });

            const resp = await api.commentAction({
              uid,
              id,
              action: 'delete',
              comment_id: commentId
            });

            console.log('删除评论接口返回:', resp);

            const resData = resp as any;
            if (resData.status === 'success') {
              await this.fetchDetailData();
              wx.showToast({ title: '评论删除成功', icon: 'success', duration: 1500 });
            } else {
              wx.showToast({ title: resData.message || '评论删除失败', icon: 'error' });
            }
          } catch (error) {
            console.error('评论删除失败:', error);
            wx.showToast({ title: '网络错误，请重试', icon: 'error' });
          }
        } else if (res.cancel) {
          // 取消删除，无需处理
        }
      }
    });
  },

  async onLikeClick() {
    // 动态更新用户uid
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        })
      }, 3000)
      return
    }
    
    if (!this.data.detailData) return;
    
    try {
      console.log('=== 点赞操作开始 ===');
      console.log('当前detailData:', this.data.detailData);
      console.log('当前is_liked:', this.data.detailData.is_liked);
      console.log('当前like数量:', this.data.detailData.like);
      
      // 检查是否有专门的点赞状态字段，如果没有则使用数量判断
      const isLiked = this.data.detailData.is_liked !== undefined 
        ? this.data.detailData.is_liked 
        : (this.data.detailData.like > 0);
      
      const action = isLiked ? 'cancel' : 'like';
      
      console.log('=== 调用点赞接口 ===');
      console.log('计算出的点赞状态:', isLiked);
      console.log('请求参数:', { 
        uid: this.data.uid, 
        id: this.data.id, 
        action 
      });
      
      const res = await api.toggleLike({
        uid: this.data.uid,
        id: this.data.id,
        action
      });
      
      console.log('点赞接口返回:', res);
      
      // 使用类型断言处理接口返回数据
      const resData = res as any;
      
      if (resData.status === 'success') {
        // 更新本地状态
        const detailData = { ...this.data.detailData! };
        
        if (isLiked) {
          // 取消点赞
          detailData.is_liked = false;
          detailData.like = Math.max(0, (detailData.like || 0) - 1);
          console.log('取消点赞后状态:', { is_liked: detailData.is_liked, like: detailData.like });
        } else {
          // 添加点赞
          detailData.is_liked = true;
          detailData.like = (detailData.like || 0) + 1;
          console.log('添加点赞后状态:', { is_liked: detailData.is_liked, like: detailData.like });
        }
        
        this.setData({ detailData });
        console.log('状态更新完成，新的detailData:', detailData);
        
        wx.showToast({
          title: isLiked ? '已取消点赞' : '已点赞',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: resData.message || '操作失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'error'
      });
    }
  },

  // 获取用户的点赞、收藏和关注状态
  async fetchUserStatus() {
    if (!this.data.uid || !this.data.id) return;
    
    try {
      console.log('=== 获取用户状态 ===');
      
      // 并行调用三个接口获取用户状态
      const [collectionRes, likeRes, followRes] = await Promise.all([
        api.getCollectionList({ uid: this.data.uid, pageIndex: 1, pageSize: 50 }),
        api.inspirationLikeList({ uid: this.data.uid }),
        api.getInspirationFollowUserList({ uid: this.data.uid })
      ]);
      
      console.log('收藏列表接口返回:', collectionRes);
      console.log('点赞列表接口返回:', likeRes);
      console.log('关注用户列表接口返回:', followRes);
      
      // 检查当前内容是否在收藏列表中（兼容不同数据结构）
      if (collectionRes) {
        const collectionList: any[] = Array.isArray((collectionRes as any).data)
          ? (collectionRes as any).data
          : (Array.isArray(collectionRes) ? (collectionRes as any) : []);
        if (Array.isArray(collectionList)) {
          const isCollected = collectionList.some((item: any) => {
            const inspirationId = item?.id || item?.inspiration_id;
            return inspirationId === this.data.id;
          });
          this.setData({ 'detailData.is_collected': isCollected });
          console.log('更新收藏状态:', isCollected);
        }
      }
      
      // 检查当前内容是否在点赞列表中（兼容不同数据结构）
      if (likeRes) {
        const likeList: any[] = Array.isArray((likeRes as any).data)
          ? (likeRes as any).data
          : (Array.isArray(likeRes) ? (likeRes as any) : []);
        if (Array.isArray(likeList)) {
          const isLiked = likeList.some((item: any) => {
            const inspirationId = item?.id || item?.inspiration_id;
            return inspirationId === this.data.id;
          });
          this.setData({ 'detailData.is_liked': isLiked });
          console.log('更新点赞状态:', isLiked);
        }
      }
      
      // 检查当前内容的作者是否在关注列表中（兼容不同数据结构）
      if (followRes && this.data.detailData && this.data.detailData.uid) {
        const followList: any[] = Array.isArray((followRes as any).data)
          ? (followRes as any).data
          : (Array.isArray(followRes) ? (followRes as any) : []);
        if (Array.isArray(followList)) {
          const isFollowed = followList.some((item: any) => {
            const followedUid = item?.uid || item?.follow_uid;
            return followedUid === this.data.detailData!.uid;
          });
          this.setData({ 'detailData.is_followed': isFollowed });
          console.log('更新关注状态:', isFollowed);
        }
      }
      
    } catch (error) {
      console.error('获取用户状态失败:', error);
      // 设置默认状态
      this.setData({
        'detailData.is_collected': false,
        'detailData.is_liked': false,
        'detailData.is_followed': false
      });
    }
  },





  // 关注按钮点击事件
  async onFollowClick(e: any) {
    // 动态更新用户uid
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        })
      }, 3000)
      return
    }
    
    const { uid } = e.currentTarget.dataset;
    if (!uid || !this.data.detailData) return;
    
    try {
      console.log('=== 关注操作开始 ===');
      console.log('关注用户uid:', uid);
      console.log('当前内容id:', this.data.id);
      console.log('当前用户uid:', this.data.uid);
      
      const action = this.data.detailData.is_followed ? 'cancel' : 'follow';
      
      console.log('=== 调用关注接口 ===');
      console.log('请求参数:', {
        action,
        follow_uid: uid,
        inspiration_id: this.data.id,
        uid: this.data.uid
      });
      
      const res = await api.followUser({
        action,
        follow_uid: uid,
        inspiration_id: this.data.id,
        uid: this.data.uid
      });
      
      console.log('关注接口返回:', res);
      
      // 使用类型断言处理接口返回数据
      const resData = res as any;
      
      if (resData.status === 'success') {
        // 更新本地关注状态
        const detailData = { ...this.data.detailData! };
        detailData.is_followed = !detailData.is_followed;
        
        this.setData({ detailData });
        console.log('关注状态更新完成:', detailData.is_followed);
        // 同步更新本地关注 uid 列表
        const list = [...this.data.followUidList];
        if (detailData.is_followed) {
          if (!list.includes(uid)) list.push(uid);
        } else {
          const idx = list.indexOf(uid);
          if (idx >= 0) list.splice(idx, 1);
        }
        this.setData({ followUidList: list });
        
        wx.showToast({
          title: detailData.is_followed ? '关注成功' : '取消关注成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: resData.message || '操作失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('关注操作失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'error'
      });
    }
  },

  onCitationClick(e: any) {
    const { link } = e.currentTarget.dataset;
    console.log('点击citation，跳转到链接:', link);
    
    if (link) {
      // 复制链接到剪贴板并提示用户
      wx.setClipboardData({
        data: link,
        success: () => {
          wx.showToast({ 
            title: '链接已复制，请在浏览器中打开', 
            icon: 'success',
            duration: 2000
          });
          
          // 显示操作菜单，让用户选择
          wx.showModal({
            title: '打开链接',
            content: '链接已复制到剪贴板，是否在浏览器中打开？',
            confirmText: '打开',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                // 在微信小程序中，我们可以尝试使用web-view或者提示用户手动打开
                wx.showToast({
                  title: '请在浏览器中粘贴链接打开',
                  icon: 'none',
                  duration: 3000
                });
              }
            }
          });
        },
        fail: () => {
          wx.showToast({ 
            title: '复制失败', 
            icon: 'error' 
          });
        }
      });
    } else {
      wx.showToast({ 
        title: '链接不可用', 
        icon: 'error' 
      });
    }
  },

  onLinkClick(e: any) {
    const { link } = e.currentTarget.dataset;
    console.log('点击链接，跳转到:', link);
    
    if (link) {
      // 复制链接到剪贴板并提示用户
      wx.setClipboardData({
        data: link,
        success: () => {
          wx.showToast({ 
            title: '链接已复制，请在浏览器中打开', 
            icon: 'success',
            duration: 2000
          });
          
          // 显示操作菜单，让用户选择
          wx.showModal({
            title: '打开链接',
            content: '链接已复制到剪贴板，是否在浏览器中打开？',
            confirmText: '打开',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                wx.showToast({
                  title: '请在浏览器中粘贴链接打开',
                  icon: 'none',
                  duration: 3000
                });
              }
            }
          });
        },
        fail: () => {
          wx.showToast({ 
            title: '复制失败', 
            icon: 'error' 
          });
        }
      });
    } else {
      wx.showToast({ 
        title: '链接不可用', 
        icon: 'error' 
      });
    }
  },

  onShareClick() {
    wx.showActionSheet({
      itemList: ['分享给好友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage'] });
            break;
          case 1:
            wx.showShareMenu({ withShareTicket: true, menus: ['shareTimeline'] });
            break;
          case 2:
            this.copyShareLink();
            break;
        }
      }
    });
  },

  copyShareLink() {
    const detailData = this.data.detailData;
    if (!detailData) return;
    
    const shareText = `${detailData.title}\n\n${detailData.content ? detailData.content.substring(0, 100) + '...' : ''}\n\n原文链接：${detailData.link || ''}`;
    wx.setClipboardData({
      data: shareText,
      success: () => wx.showToast({ title: '内容已复制', icon: 'success' })
    });
  },

  onShareAppMessage() {
    const detailData = this.data.detailData;
    return {
      title: detailData?.title || '灵感详情',
      desc: detailData?.content ? detailData.content.substring(0, 100) : '发现了一个有趣的灵感',
      path: `/pages/inspection/detail/detail?id=${this.data.id}&uid=${this.data.uid}`,
      imageUrl: detailData?.image_url || ''
    };
  },

  onShareTimeline() {
    const detailData = this.data.detailData;
    return {
      title: detailData?.title || '灵感详情',
      imageUrl: detailData?.image_url || '',
      query: `id=${this.data.id}&uid=${this.data.uid}`
    };
  },

  async fetchContentTags() {
    try {
      const userInfo = common.getAppUserInfo();
      const uid = userInfo?.uid || userInfo?.userId;
      if (!uid) return;
      
      const res = await api.getAvailableTags({ uid });
      if (res && (res as any).tags) {
        this.setData({ availableTags: (res as any).tags });
      }
    } catch (error) {
      console.error('获取标签失败:', error);
    }
  },
  
  showTagSelector() {
    this.setData({ showTagSelector: true, selectedTag: '' });
    this.fetchContentTags();
  },
  
  hideTagSelector() {
    this.setData({ showTagSelector: false, selectedTag: '' });
  },
  
  onTagSelect(e: any) {
    this.setData({ selectedTag: e.currentTarget.dataset.tag });
  },
  
  async confirmAddTag() {
    if (!this.data.selectedTag) return;
    
    try {
      const userInfo = common.getAppUserInfo();
      const uid = userInfo?.uid || userInfo?.userId;
      if (!uid) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      
      const res = await api.addTagToInspiration({
        action: 'add',
        id: this.data.id,
        uid: uid,
        tags: this.data.selectedTag
      });
      
      if (res && (res as any).status === 'success') {
        const newTags = [...this.data.contentTags];
        if (!newTags.includes(this.data.selectedTag)) {
          newTags.push(this.data.selectedTag);
        }
        
        this.setData({
          contentTags: newTags,
          showTagSelector: false,
          selectedTag: ''
        });
        
        console.log('标签添加成功，当前标签列表:', newTags);
        wx.showToast({ title: '添加成功', icon: 'success' });
      } else {
        wx.showToast({ title: '添加失败', icon: 'error' });
      }
    } catch (error) {
      console.error('添加标签失败:', error);
      wx.showToast({ title: '网络错误', icon: 'error' });
    }
  },

  onSimilarCardClick(e: any) {
    const { id, column } = e.currentTarget.dataset;
    if (!id) return;
    const key = column === 'right' ? 'similarRightColumn' : 'similarLeftColumn';
    const columnData = (this.data as any)[key] || [];
    const target = columnData.find((item: any) => item.id === id);
    if (!target) {
      wx.showToast({ title: '内容不存在', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/pages/inspection/detail/detail?id=${target.id}&uid=${target.uid || this.data.uid}&author_id=${target.username || target.uid || ''}`
    });
  },

  onSimilarAvatarClick(e: any) {
    const { uid, username } = e.currentTarget.dataset;
    if (!uid) {
      wx.showToast({ title: '作者信息缺失', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/pages/inspection/profile/profile?uid=${uid}&username=${username || ''}`
    });
  },
  
  async onSimilarCollectClick(e: any) {
    this.updateUserUid();
    
    if (!this.data.uid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login?single=true'
        });
      }, 3000);
      return;
    }
    
    const { id, column } = e.currentTarget.dataset;
    const columnKey = column === 'right' ? 'similarRightColumn' : 'similarLeftColumn';
    const columnData = ([...(this.data as any)[columnKey]] as any[]);
    const index = columnData.findIndex((item: any) => item.id === id);
    
    if (index === -1) return;
    
    const target = columnData[index];
    const isCollected = !!target.is_collected;
    const action = isCollected ? 'cancel' : 'collect';
    
    try {
      wx.showLoading({ title: action === 'collect' ? '收藏中' : '取消中', mask: true });
      await api.toggleCollection({
        uid: this.data.uid,
        id,
        action
      });
      
      const updatedItem = {
        ...target,
        is_collected: !isCollected,
        collection: this.adjustCollectionCount(target.collection, isCollected)
      };
      
      columnData[index] = updatedItem;
      const similarList = [...this.data.similarList];
      const listIndex = similarList.findIndex((item: any) => item.id === id);
      if (listIndex >= 0) similarList[listIndex] = updatedItem;
      
      this.setData({
        [columnKey]: columnData,
        similarList
      });
      
      wx.showToast({
        title: isCollected ? '已取消收藏' : '已收藏',
        icon: 'success'
      });
    } catch (error) {
      console.error('猜你喜欢收藏操作失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  adjustCollectionCount(count: number = 0, cancel: boolean) {
    if (cancel) {
      return Math.max(0, count - 1);
    }
    return count + 1;
  },

  noop() {}
}); 